package com.stn.zjx.givingtreasure.activity.userlogin;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mixiaoxiao.smoothcompoundbutton.SmoothCheckBox;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.UserLoginEvent;
import com.stn.zjx.givingtreasure.domain.UserRegisterDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxRegTool;
import com.vondear.rxtools.view.RxToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RegisterUserActivity extends BaseActivity {


    //正在发送中
    boolean isSendLoading = false;
    int seconds = 60;
    EventHandler eh;
    Disposable sendvalidate__disposable = null;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.validate_bt)
    TextView validateBt;
    @BindView(R.id.phone_edit)
    EditText phoneEdit;
    @BindView(R.id.phone_ll)
    LinearLayout phoneLl;
    @BindView(R.id.validate_tv)
    TextView validateTv;
    @BindView(R.id.validatecode_edit)
    EditText validatecodeEdit;
    @BindView(R.id.getvalidate_ll)
    LinearLayout getvalidateLl;
    @BindView(R.id.password_tv)
    TextView passwordTv;
    @BindView(R.id.password_edit)
    EditText passwordEdit;
    @BindView(R.id.confirmpassword_tv)
    TextView confirmpasswordTv;
    @BindView(R.id.confirmpassword_edit)
    EditText confirmpasswordEdit;
    @BindView(R.id.check_by)
    SmoothCheckBox checkBy;
    @BindView(R.id.agree_after_tv)
    TextView agreeAfterTv;
    @BindView(R.id.registeruser_bt)
    ButtonBgUi registeruserBt;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_user);
        ButterKnife.bind(this);
        initComponent();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.user_register));
        agreeAfterTv.setText(getString(R.string.app_name) + getString(R.string.agree_after));
        //发送验证码
        validateBt.setOnClickListener(v -> {
            if (!message_check()) {
                return;
            }
            sendValidate();
            SMSSDK.getVerificationCode("86", String.valueOf(phoneEdit.getText().toString().trim()));
        });
        //监听注册
        eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                //回调完成
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //提交验证码成功
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        runOnUiThread(() -> register(phoneEdit.getText().toString().trim(),
                                passwordEdit.getText().toString().trim()));

                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        runOnUiThread(() -> {

                            showToast(getString(R.string.sms_send_wait));
                        });

                    }
                } else {
                    runOnUiThread(() -> {
                        String str = ((Throwable) data).getMessage();
                        try {
                            JSONObject jb = new JSONObject(str);
                            showToast(jb.getString("detail"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    });
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        checkBy.setOnCheckedChangeListener((smoothCompoundButton, b) -> {
            if (b) {
                registeruserBt.setClickable(true);
                registeruserBt.setAlpha(1.0f);
            } else {
                registeruserBt.setClickable(false);
                registeruserBt.setAlpha(0.5f);
            }
        });
        registeruserBt.setOnClickListener(v -> {
            if (!register_check()) {
                return;
            }
            SMSSDK.submitVerificationCode("86", phoneEdit.getText().toString().trim(),
                    validatecodeEdit.getText().toString().trim());

        });
        registeruserBt.setClickable(false);
    }

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (eh != null) {
            SMSSDK.registerEventHandler(eh); //注册短信回调
        }

    }

    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
        }
    }

    //短信发送验证检查
    public boolean message_check() {
        if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {

            showToast(getString(R.string.phone_isnotempty));
            return false;
        }
        if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {

            showToast(getString(R.string.please_isnotreal_phone));
            return false;
        }
        if (!RxNetTool.isAvailable(this)) {
            showToast(getString(R.string.request_networkavailable));
            return false;
        }
        return true;
    }

    //注册检查
    public boolean register_check() {
        if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
            showToast(getString(R.string.phone_isnotempty));
            return false;
        }

        if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {

            showToast(getString(R.string.please_isnotreal_phone));
            return false;
        }
        if (TextUtils.isEmpty(validatecodeEdit.getText().toString().trim())) {

            showToast(getString(R.string.sms_isnotempty));
            return false;
        }
        if (TextUtils.isEmpty(passwordEdit.getText().toString().trim())) {
            showToast(getString(R.string.password_isnotempty));
            return false;
        }
        if (!ToolsUtils.checkUserPassword(passwordEdit.getText().toString().trim())) {

            showToast(getString(R.string.password_validate));
            return false;
        }
        if (TextUtils.isEmpty(confirmpasswordEdit.getText().toString().trim())) {

            showToast(getString(R.string.confirmpassword_isnotempty));
            return false;
        }
        if (!TextUtils.equals(passwordEdit.getText().toString().trim(),
                confirmpasswordEdit.getText().toString().trim())) {

            showToast(getString(R.string.password_confirm_validate));
            return false;
        }
        if (!RxNetTool.isAvailable(this)) {

            showToast(getString(R.string.request_networkavailable));
            return false;
        }
        return true;

    }

    //发送短信验证
    @SuppressLint("SetTextI18n")
    public void sendValidate() {
        sendvalidate__disposable = Observable.create((ObservableOnSubscribe<Integer>) observableEmitter -> {
            while (isSendLoading && seconds > 0) {
                seconds--;
                observableEmitter.onNext(seconds);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    sendvalidate__disposable.dispose();
                    e.printStackTrace();
                }
            }
            observableEmitter.onComplete();
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    isSendLoading = true;
                    validateBt.setBackgroundResource(R.drawable.round_darkgray_bg);
                    validateBt.setClickable(false);

                })
                .subscribe(seconds -> {
                    isSendLoading = true;
                    validateBt.setText(getString(R.string.surplus)
                            + "" + seconds + getString(R.string.seconds)
                            + getString(R.string.resend));
                }, throwable -> {
                    sendvalidate__disposable.dispose();
                    reset_sendValidate();
                }, this::reset_sendValidate);


    }


    @Override
    protected void onStop() {
        super.onStop();
        if (eh != null) {
            SMSSDK.unregisterEventHandler(eh);
        }
    }

    //重置发送短信按钮
    public void reset_sendValidate() {
        isSendLoading = false;
        validateBt.setText(getString(R.string.get_validate));
        validateBt.setBackgroundResource(R.drawable.round_default_theme_bg);
        seconds = 60;
        validateBt.setClickable(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sendvalidate__disposable != null) {
            sendvalidate__disposable.dispose();
            reset_sendValidate();
        }
    }

    //用户注册
    public void register(String phone, String password) {
        if (!RxNetTool.isAvailable(this)) {
            RxToast.error(getString(R.string.request_networkavailable));
            return;
        }
        UserNetImpl.user_reigster(phone, password, "user_reigster", new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                showLoading();
            }

            @Override
            public void onSuccess(Response<String> response) {
                if (response.isSuccessful()) {
                    if (response.body() == null) {
                        showToast(response.message());
                        return;
                    }
                    Gson gson = new Gson();
                    UserRegisterDomain domain = gson.fromJson(response.body().trim(), UserRegisterDomain.class);

                    switch (domain.getStatus()) {
                        case BaseApi.REQUEST_SUCCESS_CODE:
                            UserLoginEvent event = new UserLoginEvent(UserLoginEvent.USERLOGIN_REGISTER_FINISH,
                                    phoneEdit.getText().toString().trim(),
                                    passwordEdit.getText().toString().trim());
                            EventBus.getDefault().post(event);
                            finish();
                            break;
                        default:
                            showToast(domain.getMessage());
                            break;
                    }
                } else {
                    showToast(response.message());

                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                showToast(getString(R.string.request_please_wait));

            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (!isFinishing()) {
                    dissmissLoading();
                }
            }
        });


    }

    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

}
